package com.aust.syn;

/**
 * 线程不安全：有负数
 */
public class UnsafeBuyTickt {
    public static void main(String[] args) {

        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket, "苦逼的你").start();
        new Thread(buyTicket, "牛逼的我").start();
        new Thread(buyTicket, "可恶的他").start();

    }
}

class BuyTicket implements Runnable {

    // 票数
    private int ticketNums = 1000;
    // 停止方式
    private boolean flag = true;

    @Override
    public void run() {
        // 买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * synchronized 同步方法
     * 锁的是this
     *
     * @throws InterruptedException
     */
    private synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        // 模拟延时
        /*Thread.sleep(100);*/
        // 买票
        System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票！");
    }

}
